package com.epigeon.amadeo.engine;

import java.util.List;

import com.epigeon.amadeo.input.ActiveInput;
import com.epigeon.amadeo.input.Input;
import com.epigeon.amadeo.model.Message;
import com.epigeon.amadeo.modifier.Modifier;
import com.epigeon.amadeo.output.Output;

public class Engine {
	
	private EngineConfiguration engineConfiguration = null;
	private static Engine instance = null;
		
	public synchronized static Engine getInstance() {
		if ( instance == null ) {
			instance = new Engine();
		} 
		return instance;
	}
	
	public void activeInputNotification(ActiveInput activeInput, Message message) {
 
		for (Route route : engineConfiguration.getRoutes()) {
			if ( route.getInput().hashCode() == activeInput.hashCode() ) {
				// apply modifiers
				List<Modifier> modifiers = route.getModifiersList();
				for (Modifier modifier : modifiers) {
					message = modifier.modify(message);
				}
				// send the message to the outputs
				List<Output> outputs = route.getOutputsList();
				for (Output output : outputs) {
					List<Modifier> outputModifiers = output.getModifierList();
					for (Modifier modifier : outputModifiers) {
						message = modifier.modify(message);
					}					
					output.putMessage(message);
				}
			}
		}
	}
	
	public void setEngineConfiguration(EngineConfiguration configuration) {
		this.engineConfiguration = configuration;
	}
	
	public void registerInput(String key, Input input) {
		engineConfiguration.registerInput(key, input);
	}
	
	public void registerOutput(String key, Output output) {
		engineConfiguration.registerOutput(key, output);
	}
	
	public void registerModifier(String key, Modifier modifier) {
		engineConfiguration.registerModifier(key, modifier);
	}
		
}